package com.ssu.judea.travlog.model;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import statics.TravlogVars;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ssu.judea.travlog.vo.Attach;
import com.ssu.judea.travlog.vo.Content;
import com.ssu.judea.travlog.vo.DatePost;
import com.ssu.judea.travlog.vo.Member;
import com.ssu.judea.travlog.vo.Post;
import com.ssu.judea.travlog.vo.Result;
import com.ssu.judea.travlog.vo.ResultPost;
import com.ssu.judea.travlog.vo.ResultRecentPost;

import comm.util.RequestManager;
import comm.util.SqlMapLoader;
import comm.util.TravlogHashMap;
import comm.util.TwitterAPI;

public class AndroidDAO extends TravlogDAO{

	public void toAuthpage(HttpServletRequest request,HttpServletResponse response){
		TwitterAPI twit = new TwitterAPI();
		twit.toAuthMobilePage(request, response);
	}
	
	public void toTwitterPage(HttpServletRequest request,HttpServletResponse response) throws IOException{
		TravlogHashMap hm = RequestManager.getRequest(request);
		if(hm.get("URL")!=null){
			request.getSession().setAttribute("TWITTER_TOKEN_SECRET", hm.get("SECRET").toString());
			response.sendRedirect(hm.get("URL").toString());
		}
	}
	
	public Result writePost(TravlogHashMap hm) {
		Result result = new Result();
		//넘어오는 parameters : SEQ, OPEN(0,1,2), LAT, LOT, IMAGE(saved filename), CONTENT, SHARE
		boolean successPostSave = true;
		boolean successContentSave = true;
		boolean successImageSave = true;
		boolean successTwitterSave = true;
		
		if(hm.get("SEQ")!=null && hm.get("SEQ").toString().length()>0){
			double latitude = Double.parseDouble(hm.get("LAT").toString());
			double logngitude = Double.parseDouble(hm.get("LOT").toString());
			//우선적으로 위치 저장(Posts)
			Post post = new Post();
			post.setLatitude(latitude);
			post.setLongitude(logngitude);
			post.setMemberseq(Integer.parseInt(hm.get("SEQ").toString()));
			post.setOpen(Integer.parseInt(hm.get("OPEN").toString()));
			try {
				post.setPostseq(Integer.parseInt(sqlMapper.insert("post.regPost", post).toString()));
			} catch (NumberFormatException e) {
				logger.debug(e.getMessage());
			} catch (SQLException e) {
				logger.debug(e.getMessage());
			}
				if(post.getPostseq()<1){
					successPostSave = false;
				}
			
			//내용이 존재할경우 Content입력 
			if(hm.get("CONTENT")!=null && hm.get("CONTENT").toString().length()>0){
				Content content = new Content();
				content.setPostseq(post.getPostseq());
				content.setText(hm.get("CONTENT").toString());
				try {
					int contentSeq = Integer.parseInt(sqlMapper.insert("post.regContent", content).toString());
					if(contentSeq<1){
						successContentSave = false;
					}
				} catch (SQLException e) {
					logger.debug(e.getMessage());
				}
				
				
			}
			//첨부한이미지가 존재할 경우 Attach 입력
			if(hm.get("IMAGE")!=null && hm.get("IMAGE").toString().length()>0){
				Attach attach = new Attach();
				attach.setFile(hm.get("IMAGE").toString());
				attach.setPostseq(post.getPostseq());
				try {
					int attachSeq = Integer.parseInt(sqlMapper.insert("post.regAttach", attach).toString());
					if(attachSeq<1){
						successImageSave = false;
					}
				} catch (SQLException e) {
					logger.debug(e.getMessage());
				}
			}
			
			//트위터에 같이 포스팅 할경우 포스팅
			if(hm.get("SHARE")!=null && hm.get("SHARE").toString().equals("1")){
				Member member = null;
				try {
					member = (Member) sqlMapper.queryForObject("member.getMemberBySeq", hm.get("SEQ").toString());
				} catch (SQLException e) {
					logger.debug(e.getMessage());
				}
				String twitContent = "";
				if(hm.get("CONTENT")!=null && hm.get("CONTENT").toString().length()>0){
					twitContent = hm.get("CONTENT").toString();
				}else{
					twitContent = "My Travloging here";
				}
				if(member!=null && member.getTwitterpasskey()!=null && member.getTwitterpasskey().length()>0){
					if(twit==null)twit = new TwitterAPI();
					if(!TravlogVars.SUCCESS.equals(twit.writeTwit(member.getTwitterpasskey(), twitContent, latitude, logngitude))){					
						successTwitterSave = false;
					}
				}
			}
			String resultMsg = "";
			if(!successContentSave)resultMsg.concat("Content Save Failure.\n");
			if(!successImageSave)resultMsg.concat("Image Save Failure.\n");
			if(!successPostSave)resultMsg.concat("Location Save Failure.\n");				
			if(!successTwitterSave)resultMsg.concat("Twitter Posting Failure.\n");
			
			if(successContentSave && successImageSave && successPostSave && successTwitterSave){
				resultMsg = "All process done~";
			}
			
			result.setMessage(resultMsg);
			result.setResult(TravlogVars.SUCCESS);
		}else{
			result.setMessage("Fail to connect user info");
			result.setResult(TravlogVars.FAIL);
		}
		return result;
	}

	public String getUserPostDateList(String memberseq) {
		ArrayList<DatePost> resultList = null;
		try {
			resultList = (ArrayList<DatePost>)sqlMapper.queryForList("post.getUserPostDateList", memberseq);
		} catch (SQLException e) {
			return null;
		}
		
		if(resultList!=null){
			JSONArray jsonArr = new JSONArray();
			for(DatePost cur : resultList){
				jsonArr.put(new JSONObject(cur.toHashMap()));
			}
			
			return jsonArr.toString();
		}else{
			return TravlogVars.FAIL;
		}
	}
	
	

	public String getUserPostByDate(String serverUrl,String memberseq, String targetdate) {
		TravlogHashMap paramHm = new TravlogHashMap();
		paramHm.put("MEMBER_SEQ", memberseq);
		paramHm.put("TARGET_DATE", targetdate);
		
		ArrayList<ResultPost> resultList = null;
		
		try {
			resultList = (ArrayList<ResultPost>)sqlMapper.queryForList("post.getUserPostByDate", paramHm);
		} catch (SQLException e) {
			return null;
		}
		
		if(resultList!=null){
			JSONArray jsonArr = new JSONArray();
			for(ResultPost cur : resultList){
				cur.setAttachimageurl(serverUrl+"/"+TravlogVars.IMG_UPLOAD_PATH+"/"+cur.getAttachimageurl());
				jsonArr.put(new JSONObject(cur.toHashMap()));
			}
			return jsonArr.toString();
		}else{
			return TravlogVars.FAIL;
		}
		
	}

	public String getRecentOpenPosts() {
		ArrayList<ResultRecentPost> resultList = null;
		
		try {
			resultList = (ArrayList<ResultRecentPost>)sqlMapper.queryForList("post.getRecentOpenPosts");
		} catch (SQLException e) {
			logger.debug(e.getMessage());
			return null;
		}
		
		if(resultList!=null){
			JSONArray jsonArr = new JSONArray();
			for(ResultRecentPost cur : resultList){
				jsonArr.put(new JSONObject( cur.toHashMap()));
			}
			logger.debug(jsonArr.toString());
			return jsonArr.toString();
		}else{
			return TravlogVars.FAIL;
		}
	}

	public String getFollowersList(String curClientSeq) {
		ArrayList<Member> list = null;
		ArrayList<DatePost> datePostList = new ArrayList<DatePost>();
		
		if(sqlMapper==null)sqlMapper = SqlMapLoader.getInstance();
		
		Member mem = getMemberBySeq(curClientSeq);
		
		String passkey = mem.getTwitterpasskey();
		
		//트윗 follow 처리
		if(twit==null)twit = new TwitterAPI();
		ArrayList<Integer> followersIds = null;
		if(passkey.length()>0)
			followersIds = twit.getMyFollowersList(passkey);
		
		if(followersIds!=null && followersIds.size()>0){
			list = new ArrayList<Member>();
			for(int i = 0; i<followersIds.size();i++){
				Member currentItem = getMemberByNumber(followersIds.get(i).toString());
				
				if(currentItem!=null)list.add(currentItem);
			}
			
			logger.debug("getFollowersInfo Result"+list.size());
			
			if(list.size()>0){
				
				for(int i = 0; i<list.size();i++){
					datePostList.addAll(getUserPostDateListArrayList(String.valueOf(list.get(i).getMemberseq())));					
				}
			}
		}
		
		if(datePostList!=null){
			JSONArray jsonArr = new JSONArray();
			for(DatePost cur : datePostList){
				jsonArr.put(new JSONObject( cur.toHashMap()));
			}
			logger.debug(jsonArr.toString());
			return jsonArr.toString();
		}else{
			return TravlogVars.FAIL;
		}
		
	}
	
	
}
